package com.nine.shop.controller;


import com.nine.shop.common.ServerResponse;
import com.nine.shop.model.Goods;
import com.nine.shop.service.CartService;
import com.nine.shop.service.GoodsService;
import com.nine.shop.service.TypeService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * @author hty
 * Create on 2019/8/17
 */
@RestController
@RequestMapping(value="api/shopping/goods")
public class GoodsController extends BaseController {
    @Resource
    private GoodsService goodsService;
    @Resource
    private TypeService typeService;
    @Resource
    private CartService cartService;

    /**
     * @param current 当前页码
     * @param size    每页大小
     * @param type  用户ID
     */
    @CrossOrigin
    @RequestMapping(value = "searchgoodsbytype.do",method = RequestMethod.GET)
    public ServerResponse findByTypeIdPage(@RequestParam(name = "current", defaultValue = "1") Integer current,
                                           @RequestParam(name = "size", defaultValue = "5") Integer size,
                                           @RequestParam(name = "type", defaultValue = "1") Integer type) {

        if (type == null) return ServerResponse.createByErrorMsg("该类别不存在");
        return ServerResponse.createBySuccess(goodsService.findByTypeIdPage(current, size, type));
    }

    /**
     * lzx
     * 查询所有商品
     * @param current
     * @param size
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "serachallgoodspage.do",method = RequestMethod.GET)
    public ServerResponse serachAllGoodsPage(@RequestParam(name = "current", defaultValue = "1") Integer current,
                                           @RequestParam(name = "size", defaultValue = "5") Integer size) {
        return ServerResponse.createBySuccess(goodsService.findGoodsPage(current, size));
    }
    /**
     *
     * @param goodsid
     * @return
     */

    @CrossOrigin
    @RequestMapping(value = "searchgoodsbyid.do",method = RequestMethod.POST)
    public ServerResponse findByGoodsId( @RequestParam(name = "goodsid") Integer goodsid) {
        Goods goods = goodsService.findByGoodsId(goodsid);
        if (goods == null) return ServerResponse.createByErrorMsg("商品不存在");
        if (goods.getStatus() == 1) return ServerResponse.createByErrorMsg("商品已下架");
        return ServerResponse.createBySuccess(goodsService.findByGoodsId(goodsid));
    }


    @CrossOrigin
    @RequestMapping(value = "addgoodstocart.do",method = RequestMethod.POST)
    public ServerResponse addGoodsToCart(@RequestParam(name = "goodsid") Integer goodsid,
                                         @RequestParam(name = "amount") Integer amount) {
        //Integer userid =1;
        Integer userid= super.getUser().getId();
        if (goodsid == null || userid == null || amount == null) {
            return ServerResponse.createByErrorMsg("添加失败");
        } else {
             return cartService.same(userid,goodsid,amount);
        }
    }
}